package org.neatsee.bookshop.filter;

/*
	AdminAuthenticationFilter is to validate the admin's identity !
*/

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.neatsee.bookshop.action.Constant;

public class AdminAuthenticationFilter implements Filter {
	private static String LOGIN_PAGE = "/login.jsp";

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;

		HttpServletResponse res = (HttpServletResponse) response;

		HttpSession session = req.getSession();

		if ((session == null)
				|| (session.getAttribute(Constant.USER_NAME) == null)
				|| (!session.getAttribute(Constant.ROLE).equals(
						Constant.ADMIN_ROLE))) {
			session.removeAttribute(Constant.USER_NAME);
			session.removeAttribute(Constant.ROLE);
			res.sendRedirect(req.getContextPath() + LOGIN_PAGE);
			return;
		}

		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
	}
}